<template>
  <el-dialog
    :append-to-body="true"
    :title="'工作实施方案'"
    :visible.sync="visible"
    custom-class="ledger"
    fullscreen top="5vh"
    width="1200px"
    :before-close="cancelDialog">
    <div class="colums">
      <div class="colums_left">
        <div class="colums_left_middle">
          <div class="middleForm ledger">
            <el-form ref="dataForm" :model="form" class="el-dialog__body" label-width="100px">
              <div class="title">基本信息</div>
              <el-row>
                <el-col :span="12">
                  <el-form-item label-width="140px" label="项目名称: " prop="projectName">
                    {{ form.projectName }}
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label-width="110px" label="审计区间:">
                    <span v-if="form.auditStartDate" style="margin-right: 5px;">{{ form.auditStartDate }} 至</span>
                    <span style="margin-left: 5px;">{{ form.auditEndDate }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6">
                  <el-form-item label-width="140px" label="被审计单位:" prop="auditedCompanyName">
                    {{ form.auditedCompanyName }}
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label-width="110px" label="被审计个人:">
                    {{ form.auditedUserNames }}
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label-width="110px" label="审计类型:" prop="auditType">
                    <DictTag :options="dict.type.audit_type" :value="form.auditType"></DictTag>
                  </el-form-item>
                </el-col>
                <el-col :span="5">
                  <el-form-item label-width="100px" label="是否披露:" prop="isPublish">
                    <div v-if="Number(form.isPublish) === 0">
                      <span>否</span>
                    </div>
                    <div v-else>
                      <span>是</span>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-row v-if="form.auditType === 1">
                  <el-col :span="6">
                    <el-form-item label-width="140px" label="审计子类型:" prop="auditTypeSub">
                      {{form.auditTypeSub}}
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label-width="110px" label="任职区间:" prop="tenureDates">
                      <span v-if="form.tenureStartDate" style="margin-right: 5px;">{{ form.tenureStartDate }} 至</span>
                      <span style="margin-left: 5px;">{{ form.tenureEndDate }}</span>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-row>
              <div class="title">工作方案</div>
<!--              <el-row>-->
<!--                <el-col>-->
<!--                  <el-form-item label-width="90px"  label="被审计单位基本情况:">-->
<!--                    <el-input v-model="form.auditSubjectProfile" :autosize="{ minRows: 2}" type="textarea"></el-input>-->
<!--                  </el-form-item>-->
<!--                </el-col>-->
<!--              </el-row>-->
              <el-row>
                <el-col>
                  <el-form-item label-width="140px" label="审计目的:">
                    <el-input v-model="form.auditPurpose" :autosize="{ minRows: 2}" type="textarea"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col>
                  <el-form-item label-width="140px" label="审计范围:" prop="auditScope" :rules="{required: true, message: '审计范围不能为空', trigger: ['focus', 'change']}">
                    <el-input v-model="form.auditScope" :autosize="{ minRows: 2}" type="textarea"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <div class="title">审计重点</div>
              <el-row>
                <el-col>
                  <el-button icon="el-icon-plus" size="small" type="primary" @click="onAddItem">新建</el-button>
                    <el-button icon="el-icon-document-copy" @click="addSelectedRow">复制</el-button>
                    <el-button icon="el-icon-delete" @click="deleteSelectedRows">删除</el-button>
                  <el-button icon="el-icon-delete-solid" @click="clearTableData">删除全部</el-button>
                </el-col>
              </el-row>
              <el-row>
                <el-col>
                  <el-table
                    ref="table"
                    :data="tableData"
                    :model="tableData"
                    v-loading="loading"
                    style="width: 100%"
                    max-height="450"
                    highlight-current-row
                    @selection-change="updateSelectedRows"
                    @current-change="handleCurrentChange"
                  >
                    <el-table-column type="selection" width="55" align="center"></el-table-column>
                    <el-table-column label="序号" width="100">
                      <template #default="{ $index }">
                        <span>{{ $index + 1 }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="标题" width="250">
                      <template #default="{ row }">
                        <el-input v-model="row.keynoteTitle" type="text"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="内容">
                      <template #default="{ row }">
                        <el-input v-model="row.keynoteContent" type="textarea" :autosize="{ minRows: 1}"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="应对措施">
                      <template #default="{ row }">
                        <el-input v-model="row.responseMeasures" type="textarea" :autosize="{ minRows: 1}"></el-input>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-col>
              </el-row>
              <div class="title">工作安排</div>
              <el-row>
                <el-col :span="6">
                  <el-form-item label-width="140px" label="审计组组长:" prop="auditLeader" :rules="{required: true, message: '审计组组长不能为空', trigger: ['blur', 'change']}">
                    <el-input v-model="form.auditLeader" @focus="showTransferDialog(['auditLeaderId','auditLeader'], 'auditUser', false, form.assistCompanyId)" :readonly="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label-width="110px" label="协审单位:" prop="assistCompanyName">
                    <span style="margin-left: 15px; font-size: 13px;">{{ form.assistCompanyName }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label-width="110px" label="协审单位组长:" prop="assistLeader" :rules="{required: true, message: '协审单位组长不能为空', trigger: ['blur', 'change']}">
                    <el-input v-model="form.assistLeader" @focus="showTransferDialog(['assistLeaderId','assistLeader'], 'user', false, form.assistCompanyId)" :readonly="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6">
                  <el-form-item label-width="140px" label="被审计单位联络员:" prop="auditedCompanyUserName" :rules="{required: true, message: '被审计单位联络员不能为空', trigger: ['blur', 'change']}">
                    <el-input v-model="form.auditedCompanyUserName" @focus="showTransferDialog(['auditedCompanyUserId','auditedCompanyUserName'], 'user', false, form.auditedCompanyId)" :readonly="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label-width="110px" label="协审单位主审:" prop="assistJudge" :rules="{required: true, message: '协审单位主审不能为空', trigger: ['blur', 'change']}">
                    <el-input v-model="form.assistJudge" @focus="showTransferDialog(['assistJudgeId','assistJudge'], 'user', false, form.assistCompanyId)" :readonly="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label-width="110px" label="审计组成员:" prop="assistMembers" :rules="{required: true, message: '审计组成员不能为空', trigger: ['blur', 'change']}">
                    <el-input v-model="form.assistMembers" @focus="showTransferDialog(['assistMemberIds','assistMembers'], 'user', true, form.assistCompanyId)" :readonly="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label-width="140px" label="计划工作时间:">
                    <el-date-picker placement="bottom-start" v-model="form.projectDates" value-format="yyyy-MM-dd" type="daterange" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label-width="110px" label="实施工作时间:">
                    <el-date-picker placement="bottom-start" v-model="form.workDates" value-format="yyyy-MM-dd" type="daterange" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <div class="title">实施方案文书</div>
              <el-row>
                <el-col >
                  <el-form-item label-width="140px" label="实施方案审批表:">
                    <web-document :pageType="'projectApply'" :form-data="form" readWord="edit" @createWordFile="wordFileHandle" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button icon="el-icon-close" size="small" @click="cancelDialog">关闭</el-button>
              <el-button icon="el-icon-check" size="small" type="primary" @click="submit">保存</el-button>
              <el-button type="primary" size="small" icon="el-icon-check" @click="submitAudit">保存送审</el-button>
            </span>
          </div>
        </div>
      </div>
    </div>
    <FormTransfer :transferDialog="transferDialog" :transferDialogType="transferDialogType" :multiple="transferDialogMultiple" :transferCurrent="transferCurrent" @transferData="transferDataHandle" @closeTransfer="closeTransfer"/>
    <ChoseProject ref="ChoseProject" @setValue="projectDataHandle"/>

  </el-dialog>

</template>

<script>
import FormTransfer from "@/components/form/transfer";
import ChoseProject from "@/components/audited/ChoseProject";
import {getApply, getApplyByProjectId, submit, submitAudit} from "@/api/adis/project/projectApply";
import WebDocument from '@/components/form/webDocument.vue';

export default {
  name: 'applyForm',
  props: {
    id: {
      type: String,
      default: ''
    }
  },
  components: {
    FormTransfer,
    ChoseProject,
    WebDocument
  },
  mounted() { // 检测prop中id的值
    if (this.id) { // 如果不为空，开始初始化页面
      this.init({ projectId: this.id });
    }
  },
  dictTypes: ['audit_type', 'audit_type_1_sub'],
  data() {
    return {
      visible: false,
      loading: false,
      multiple: false,
      transferDialog: false,
      transferDialogType: '',
      transferDialogTypeArr: [],
      transferDialogMultiple: false,
      transferCurrent: {},
      templateForm: [],
      form: {
        auditedCompanyUserName: '',
        keynoteTitle: '',
        keynoteContent: '',
        responseMeasures: '',
      },
      tableData: [ // 审计重点数据
        {
          templateId: 1,
        }
      ],
      selectedRows: [], // 存储选中的行数据
      selectedRow: {},
    }
  },
  watch: {
    // 检测资料清单，如果被全数删除，立即补充一条空的清单
    tableData(val){
      if (val.length < 1){
        this.onAddItem(this.tableData)
      }
      this.$set(this.form, "keynoteList", this.tableData);
      console.log(this.form.keynoteList)
    },
  },
  methods: {
    init(params) {
      this.$nextTick(() => {
        function handleApplyResponse(applyResponse) {
          if (applyResponse.workStartDate && applyResponse.workEndDate) {
            applyResponse.workDates = [applyResponse.workStartDate, applyResponse.workEndDate];
          }
          if (applyResponse.projectStartDate && applyResponse.projectEndDate) {
            applyResponse.projectDates = [applyResponse.projectStartDate, applyResponse.projectEndDate];
          }
          this.visible = true // 更改页面状态

          // 打开页面后再加载tableData,避免出现文本框渲染错误的情况
          if (applyResponse.keynoteList && applyResponse.keynoteList.length > 0) {
            this.loading = true
            setTimeout(() => {
              this.tableData = applyResponse.keynoteList || []
              this.loading = false
            }, 500)
          }
          this.$set(this, "form", applyResponse);
        }

        if (params.applyId) {
          getApply(params.applyId).then(applyResponse => {
            handleApplyResponse.call(this, applyResponse.data.data);
          });
        } else if (params.projectId) {
          getApplyByProjectId(params.projectId).then(applyResponse => {
            handleApplyResponse.call(this, applyResponse.data.data);
          });
        }
      })
    },
    showProjectDialog() {
      this.$nextTick(() => {
        this.$refs.ChoseProject.initParams({isEngineering: false, isTermination: false});
      })
    },
    projectDataHandle(row) {
      this.templateForm = this.form
      row.auditDates = [row.auditStartDate, row.auditEndDate];
      row.workDates = [row.workStartDate, row.workEndDate];
      row.projectDates = [row.projectStartDate, row.projectEndDate];
      row.auditStatus = 0
      this.$set(this, "form", Object.assign({}, this.form, row));
    },
    // 表单提交
    submit() {
      console.log(this.form)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.fileList && this.fileList.map((file) => {
            this.form.fileUrl = file.response ? file.response.data.url : file.url
          });
          // 将表单中的时间数组分装成对应的开始时间和结束时间
          const dateFields = ['audit', 'project', 'work', 'prepare', 'apply', 'finish'];

          dateFields.forEach(field => {
            const dates = this.form[`${field}Dates`];
            if (dates) {
              this.form[`${field}StartDate`] = dates[0];
              this.form[`${field}EndDate`] = dates[1];
            }
          });

          let count = 0
          try{
            this.tableData.forEach((item, i) => {
              if(!item.keynoteTitle){
                this.$message({
                  type: "warning",
                  message: '第' + (i + 1) + "行重点标题不能为空"
                });
                count++
                throw Error();
              }
              if(!item.keynoteContent){
                this.$message({
                  type: "warning",
                  message: '第' + (i + 1) + "行重点内容不能为空"
                });
                count++
                throw Error();
              }
            })
          }catch(e){
            console.log(e)
          }
          if (count > 0) return

          this.form.keynoteList = this.tableData
          submit(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.cancelDialog();
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    submitAudit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.fileList && this.fileList.map((file) => {
            this.form.fileUrl = file.response ? file.response.data.url : file.url
          });
          /** ======================== 时间数组拆装 - start ======================== */
            // 将表单中的时间数组分装成对应的开始时间和结束时间
          const dateFields = ['audit', 'project', 'work', 'prepare', 'apply', 'finish'];

          dateFields.forEach(field => {
            const dates = this.form[`${field}Dates`];
            if (dates) {
              this.form[`${field}StartDate`] = dates[0];
              this.form[`${field}EndDate`] = dates[1];
            }
          });
          /** ======================== 时间数组拆装 - end ======================== */

          let count = 0
          try{
            this.tableData.forEach((item, i) => {
              if(!item.keynoteTitle){
                this.$message({
                  type: "warning",
                  message: '第' + (i + 1) + "行重点标题不能为空"
                });
                count++
                throw Error();
              }
              if(!item.keynoteContent){
                this.$message({
                  type: "warning",
                  message: '第' + (i + 1) + "行重点内容不能为空"
                });
                count++
                throw Error();
              }
            })
          }catch(e){
            console.log(e)
          }
          if (count > 0) return

          this.form.keynoteList = this.tableData
          submitAudit(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.cancelDialog();
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    //重置表单
    cancelDialog() {
      this.visible = false
      this.$refs['dataForm'].resetFields()
      this.$emit('cancelDialog', {})
      this.clearTableData();
    },
    showTransferDialog(transferDialogArr, transferDialogType, transferDialogMultiple, transferDialogQuery) {
      this.transferDialogArr = transferDialogArr; // 表单字段
      this.transferDialogType = transferDialogType; // 判断类型user:人员，unit:职位，department:部门,company:单位,plan:计划等
      this.transferDialogMultiple = transferDialogMultiple; // 是否多选
      if (transferDialogType === 'company') {
        this.transferCurrent.type = transferDialogQuery;
      }
      if (transferDialogType === 'user') {
        if(!transferDialogQuery) {
          this.$message({
            type: "warning",
            message: "请先选择单位!"
          });
          return
        }
        this.transferCurrent.deptId = transferDialogQuery;
      }
      //重组数组name和id
      this.transferCurrent.currentval = []
      if(this.form[transferDialogArr[0]]) {
        if (this.form[transferDialogArr[0]].indexOf(',') > -1) {
          this.form[transferDialogArr[0]].split(',').forEach((item, i) => {
            this.transferCurrent.currentval.push({name: this.form[transferDialogArr[1]].split(',')[i], id: item})
          })
        } else {
          this.transferCurrent.currentval = [{name: this.form[transferDialogArr[1]], id: this.form[transferDialogArr[0]]}]
        }
      }
      this.transferDialog = true;
    },
    closeTransfer() {
      this.transferDialog = false
      this.transferDialogType = ''
    },
    // 已选定数据的更新判断
    transferDataHandle(e) {
      this.transferDialog = false
      let currentval = [], currentLabel = []
      if (e.list.length > 0) {
        if (e.list.length > 1) {
          e.list.forEach(item => {
            currentval.push(item.id)
            currentLabel.push(item.name)
          })
        } else {
          currentval = [e.list[0].id]
          currentLabel = [e.list[0].name]
        }
        this.$set(this.form, this.transferDialogArr[0], currentval.join(','))
        this.$set(this.form, this.transferDialogArr[1], currentLabel.join(','))
      } else { // 如果返回的数据为空，也将当前页面数值清空
        this.$set(this.form, this.transferDialogArr[0], '')
        this.$set(this.form, this.transferDialogArr[1], '')
      }
      console.log(this.form, 'this.form')
      this.transferDialogType = ''
    },
    // -- 审计重点
    addSelectedRow() {
      if (this.selectedRows.length > 0) {
        this.selectedRows.forEach((selectedRow) => {
          const index = this.tableData.indexOf(selectedRow);
          if (index !== -1) {
            this.onAddItem(selectedRow)
          }
        });
      } else if (Object.keys(this.selectedRow).length !== 0){
        this.onAddItem(this.selectedRow)
      } else {
        this.$message({
          type: "warning",
          message: "请选择一条数据!"
        });
      }
    },
    clearTableData() {
      this.tableData = [];
    },
    onAddItem(val) {
      // 在这里添加添加新项目的逻辑
      if (!this.tableData) this.tableData = []
      this.tableData.push({
        templateId: this.tableData.length+1,
        keynoteTitle: val.keynoteTitle || '',
        keynoteContent: val.keynoteContent || '',
        responseMeasures: val.responseMeasures || '',
      })
    },
    deleteSelectedRows() {
      if (this.selectedRows.length > 0) {
        this.selectedRows.forEach((selectedRow) => {
          const index = this.tableData.indexOf(selectedRow);
          if (index !== -1) {
            this.tableData.splice(index, 1);
          }
        });
       } else if (Object.keys(this.selectedRow).length !== 0){
        const index = this.tableData.indexOf(this.selectedRow);
        if (index !== -1) {
          this.tableData.splice(index, 1);
        }
      } else {
        this.$message({
          type: "warning",
          message: "请选择一条数据!"
        });
      }
    },
    updateSelectedRows(selection) {
      this.selectedRows = selection;
    },
    handleCurrentChange(selection){
      this.selectedRow = selection;
    },

    wordFileHandle(e) {
      this.$set(this.form, "wordFile", e.wordFile);
      this.$set(this.form, "applyId", e.id);
    }
  }
}
</script>
